import navigateTo from '@/utils/navigator';

export const useSearch = defineStore(
    'search',
    () => {
        let currentTitle = $ref('');
        let history = $ref<string[]>([]);

        // 关键字搜索历史记录排序
        function search(content: string) {
            if (content) {
                if (history.includes(content))
                    history = history.sort((a) => (a === content ? -1 : 1));
                else history.unshift(content);
                history.length > 10 && history.pop();
            }
            navigateTo(`/pages/search/index?content=${content}`);
        }

        // 清除历史记录
        function clearHistory() {
            history = [];
        }

        // 设置输入框显示值
        function setCurrentTitle(content: string) {
            currentTitle = content;
        }

        return $$({
            history,
            currentTitle,
            search,
            clearHistory,
            setCurrentTitle,
        });
    },
    {
        persist: true,
    }
);

